package com.huobaibai.conf;

import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.security.config.annotation.authentication.builders.AuthenticationManagerBuilder;
import org.springframework.security.config.annotation.web.builders.HttpSecurity;
import org.springframework.security.config.annotation.web.builders.WebSecurity;
import org.springframework.security.config.annotation.web.configuration.EnableWebSecurity;
import org.springframework.security.config.annotation.web.configuration.WebSecurityConfigurerAdapter;
import org.springframework.security.core.userdetails.UserDetailsService;

import com.huobaibai.service.security.CustomUserService;
@Configuration
@EnableWebSecurity
public class WebSecurityConfig extends WebSecurityConfigurerAdapter {
//
//	@Override
//	protected void configure(HttpSecurity http) throws Exception {
//
//		http 
//		.authorizeRequests()
//        .antMatchers("/", "/home","/remove/","/save").permitAll()
//        .anyRequest().authenticated()
//        .and()
//    .formLogin()
//        .loginPage("/login")
//        .permitAll()
//        .and()
//    .logout()
//        .permitAll();
//	}
//	
//	 @Autowired
//	    public void configureGlobal(AuthenticationManagerBuilder auth) throws Exception {
//	        auth
//	            .inMemoryAuthentication()
//	                .withUser("user").password("password").roles("USER");
//	    }
	/**
	 * 注册CustomUserService类
	 */
	@Bean
	UserDetailsService customUserService() {
		return new CustomUserService();
	}

	
	
	/**
	 * 角色授权，用户认证
	 */
	@Override
	protected void configure(AuthenticationManagerBuilder auth) throws Exception {
		System.out.println("use configure AuthenticationManagerBuilder");
		auth.userDetailsService(customUserService());//接受一个实现userDetailsService 接口的实现类引用
	}

	/**
	 * 授权
	 */
	@Override
	protected void configure(HttpSecurity http) throws Exception {
		System.out.println("use configure HttpSecurity");
		http.authorizeRequests()
		.anyRequest().authenticated()//任何链接去验证,无验证消息或不是登录界面需到loginpage
		.and()
		.formLogin()
		.loginPage("/login")
		.defaultSuccessUrl("/index")
		.failureUrl("/login?error")
		.permitAll()
		.and()
		.logout()
		.logoutUrl("/custom-logout")
		.logoutSuccessUrl("/logout-success")
		.permitAll();
		
	
	}
	

	 @Override
	    public void configure(WebSecurity web) throws Exception {
	        //解决静态资源被拦截的问题
		 System.out.println("use configure WebSecurity");
	        web.ignoring().antMatchers("/css/**");
	    }
	
	
}
